﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Renren.Services;
using Utils.MD5;
using System.Xml.Linq;

namespace Renren.ServiceProviders
{
    public class RenrenServiceProvider : ServiceProvider
    {
        public readonly static RenrenServiceProvider Instance = new RenrenServiceProvider();

        public override bool CheckResponseResult(string result)
        {
            var root = XElement.Parse(result);
            var ns = root.GetDefaultNamespace();
            if (root.Name.LocalName.StartsWith("error"))
            {
                string errorCode = root.Element("error_code").Value;
                string errorMessage = root.Element("error_msg").Value;
                NotifyResponseError(errorCode, errorMessage);
                return false;
            }
            return true;
        }

        protected override string ApiUriBase
        {
            get { return "http://api.renren.com/restserver.do"; }
        }

        protected override Dictionary<string, string> GetFinalParameters(Dictionary<string, string> parameters)
        {
            parameters.Add("access_token", RenrenSettings.AccessToken);
            parameters.Add("v", "1.0");
            parameters.Add("call_id", DateTime.Now.Millisecond.ToString());
            parameters.Add("format", "XML");
            parameters.Add("api_key", RenrenSettings.ApiKey);
            parameters.Add("sig", SignParams(parameters));
            return parameters;
        }

        private RenrenServiceProvider() : base(ServiceProviderType.Renren) { }

        private string SignParams(Dictionary<string, string> parameters)
        {
            string str = null;
            foreach (var param in parameters.OrderBy(entry => entry.Key))
            {
                str += param.Key + "=" + param.Value;
            }
            str += RenrenSettings.ApiSecret;

            StringBuilder sb = new StringBuilder();
            foreach (var ch in MD5Core.GetHash(Encoding.UTF8.GetBytes(str)))
            {
                sb.Append(ch.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
